//
//  LogionViewController.swift
//  VenusMaster
//
//  Created by qurongxiang on 2018/11/10.
//  Copyright © 2018年 zhaowang. All rights reserved.
//

import UIKit
import SwiftyJSON

class LogionViewController: UIViewController {
    fileprivate var cycyleTimer : Timer?
    fileprivate var timeNum:Int = 60
    fileprivate var currentJson = JSON()
    fileprivate var getCodeBool = false
    
    let logoImgView:UIImageView = UIImageView()
    fileprivate var telTextField:UITextField =  UITextField()
    fileprivate var codeTextField:UITextField =  UITextField()
    fileprivate var getCodeBtn:UIButton =  UIButton(type: .custom)
    fileprivate var loginBtn:UIButton =  UIButton(type: .custom)
    fileprivate var manualBtn:UIButton =  UIButton(type: .custom)
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
}


// MARK: - 逻辑
extension LogionViewController {
    
    ///获取验证码
    @objc func clickCodeAction(btn:UIButton) {
        let tel = self.telTextField.text!
        if  !tel.validateTel() {
            self.hudLoadMessage("手机号不正确")
            return
        }
        addCycleTimer()
        let dict = ["phone":tel,
                    "sign":"123"] as [String : Any]
        NetworkTools.shareInstance.loadData(.get, URLString: kgetCheckCode, parameters: dict) { [unowned self](result, error) in
            if error {
                self.hudError()
            }else {
                let json = JSON(result as Any)
                self.currentJson = json
                self.getCodeBool = true
            }
        }
    }
    
    @objc func clickLoginAction(btn:UIButton) {
        
        if !getCodeBool {
            hudLoadMessage("还未获取验证码")
            return
        }
        
        
        if (codeTextField.text?.count)! < 4 {
            hudLoadMessage("输入验证码")
            return
        }
        
        self.login(recommend: "")
        
        /*
        if !currentJson["data"]["registered"].boolValue {
            let alertController = UIAlertController(title: "推荐人",
                                                    message: "输入推荐人的手机号码", preferredStyle: .alert)
            alertController.addTextField {
                (textField: UITextField!) -> Void in
                textField.placeholder = "可为空"
            }
            
            let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
            let okAction = UIAlertAction(title: "继续", style: .default, handler: {
                action in
                let login = alertController.textFields!.first!
                let tel = login.text!
                if  !tel.validateTel() {
                    self.hudLoadMessage("手机号不正确")
                    return
                }
                self.login(recommend: tel)
            })
            alertController.addAction(cancelAction)
            alertController.addAction(okAction)
            self.present(alertController, animated: true, completion: nil)
        }else {
            self.login(recommend: "")
        }
        */
        
    }
    
    @objc func clickManualAction(btn:UIButton) {
        hudLoadMessage("用户协议")
    }
    
    
    func login(recommend:String) {
        self.hudLoad()
        let dict = [
            "phone": telTextField.text ?? "",
            "recommendPhone": recommend,
            "role": "0"
            ] as [String : Any]
        
        var apif = ""
        if currentJson["data"]["userId"].intValue == 0 {
            apif = "?timestamp=11&sign=22"
        }else {
            apif = "?timestamp=11&sign=22&operatorId=" + String(currentJson["data"]["userId"].intValue)
        }
        
        TempNetTool.post( kHost + "/common/login" + apif + "&checkCode=" + codeTextField.text!, parameters: dict, progress: { (progress) in
        }, success: {[weak self] (result) in
            self?.hudHide()
            let josn = JSON(result as Any)
            if josn["resCode"].stringValue != "login-002" && josn["resCode"].stringValue != "login-001" {
                self?.hudLoadMessage(josn["msg"].stringValue)
                return
            }
           
            guard let resultDict = result as? [String : NSObject] else { return }
            guard let data = resultDict["data"] as? [String : NSObject] else { return }
            let model = UserModel.tmSpeelBreak(data)
            UserInfo.shareInstance.setUserModel(model: model)
            UMessage.setAlias(String(model.id), type: "ALIAS_TYPE.DIPAI", response: { (result, error) in
                print("友盟：",model.id)
            })
            UIApplication.shared.keyWindow?.rootViewController = MPTabBarController()
        }) { [weak self] (error) in
            self?.hudLoadMessage("请稍后再试")
        }
    }
}


extension LogionViewController {
    func setupUI() {
        view.backgroundColor = UIColor.init(hex: "65BBE4")
        view.addSubview(logoImgView)
        view.addSubview(telTextField)
        
        logoImgView.image = UIImage(named: "login_logo")
        logoImgView.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(150)
            make.size.equalTo(CGSize(width: 280, height: 50))
            make.centerX.equalToSuperview()
        }
        let leftEmptyView = UIView()
        leftEmptyView.frame = CGRect(x: 0, y: 0, width: 20, height: 40)
        
        
        let left2EmptyView = UIView()
        left2EmptyView.frame = CGRect(x: 0, y: 0, width: 20, height: 40)
        view.addSubview(telTextField)
        telTextField.snp.makeConstraints { (make) in
            make.top.equalTo(logoImgView.snp.bottom).offset(30)
            make.left.equalToSuperview().offset(30)
            make.right.equalToSuperview().inset(30)
            make.height.equalTo(40)
        }
        telTextField.keyboardType = .numberPad
        telTextField.font = UIFont.systemFont(ofSize: 14)
        telTextField.textColor = UIColor.white
        telTextField.placeholder = "请输入手机号"
        telTextField.backgroundColor = UIColor(hex: "97D0F3", alpha: 0.5)
        telTextField.fastCornerRadius(value: 4)
        telTextField.setValue(UIColor.white, forKeyPath: "_placeholderLabel.textColor")
        telTextField.leftView = leftEmptyView
        telTextField.leftViewMode = .always
        
        
        view.addSubview(getCodeBtn)
        getCodeBtn.setTitle("获取验证码", for: .normal)
        getCodeBtn.snp.makeConstraints { (make) in
            make.size.equalTo(CGSize(width: 100, height: 40))
            make.top.equalTo(telTextField.snp.bottom).offset(30)
            make.right.equalToSuperview().inset(30)
        }
        getCodeBtn.backgroundColor = UIColor(hex: "97D0F3", alpha: 0.5)
        getCodeBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        getCodeBtn.setTitleColor(UIColor.white, for: .normal)
        getCodeBtn.fastCornerRadius(value: 4)
        getCodeBtn.addTarget(self, action: #selector(clickCodeAction(btn:)), for: .touchUpInside)
        
        view.addSubview(codeTextField)
        codeTextField.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(30)
            make.right.equalTo(getCodeBtn.snp.left).inset(-20)
            make.height.equalTo(40)
            make.centerY.equalTo(getCodeBtn)
        }
        codeTextField.keyboardType = .numberPad
        codeTextField.font = UIFont.systemFont(ofSize: 14)
        codeTextField.textColor = UIColor.white
        codeTextField.placeholder = "请输入验证码"
        codeTextField.fastCornerRadius(value: 4)
        codeTextField.backgroundColor = UIColor(hex: "97D0F3", alpha: 0.5)
        codeTextField.setValue(UIColor.white, forKeyPath: "_placeholderLabel.textColor")
        codeTextField.leftView = left2EmptyView
        codeTextField.leftViewMode = .always
        
        view.addSubview(loginBtn)
        loginBtn.snp.makeConstraints { (make) in
            make.top.equalTo(codeTextField.snp.bottom).offset(80)
            make.left.equalToSuperview().offset(30)
            make.right.equalToSuperview().inset(30)
            make.height.equalTo(40)
        }
        loginBtn.fastCornerRadius(value: 4)
        loginBtn.backgroundColor = UIColor.white
        loginBtn.setTitleColor(UIColor.gray, for: .normal)
        loginBtn.setTitleColor(UIColor.init(hex: "65BBE4"), for: .selected)
        loginBtn.titleLabel?.font = UIFont.systemFont(ofSize: 18)
        loginBtn.setTitle("登 录", for: .normal)
        loginBtn.addTarget(self, action: #selector(clickLoginAction(btn:)), for: .touchUpInside)
        
        view.addSubview(manualBtn)
        manualBtn.setTitle("登录即表示您已经同意《用户使用手册》", for: .normal)
        manualBtn.setTitleColor(UIColor.white, for: .normal)
        manualBtn.titleLabel?.font = UIFont.systemFont(ofSize: 12)
        manualBtn.snp.makeConstraints { (make) in
            make.top.equalTo(loginBtn.snp.bottom).offset(10)
            make.centerX.equalTo(loginBtn)
        }
        manualBtn.addTarget(self, action: #selector(clickManualAction(btn:)), for: .touchUpInside)
    }
    
}

extension LogionViewController {
    // 添加定时器
    fileprivate func addCycleTimer() {
        cycyleTimer = Timer(timeInterval: 1.0, target: self, selector: #selector(self.scrollToNext), userInfo: nil, repeats: true)
        RunLoop.main.add(cycyleTimer!, forMode:.common)
    }
    
    // 移除定时器
    fileprivate func removeCycleTimer() {
        cycyleTimer?.invalidate()
        cycyleTimer = nil
    }
    
    // 定时器的方法
    @objc fileprivate func scrollToNext() {
        self.getCodeBtn.isUserInteractionEnabled = false
        timeNum = timeNum - 1;
        getCodeBtn .setTitle("\(timeNum) 秒", for: .normal)
        if (timeNum == 0) {
            self.getCodeBtn.isUserInteractionEnabled = true
            timeNum = 10;
            getCodeBtn .setTitle("获取验证码", for: .normal)
            removeCycleTimer()
        }
    }
}
